<template>
  <div class="food-content-box">
    <el-breadcrumb
      separator="/"
      class="page-title"
    >
      <el-breadcrumb-item :to="{ path: '/shopUser' }">Users</el-breadcrumb-item>
      <el-breadcrumb-item>New&Edit</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="search-box container-padding">
      <el-form
        :inline="true"
        label-position="top"
        :model="submitForm"
        :rules="rules"
        size="mini"
        ref="submitForm"
        v-loading="loading"
        class="form-min-width"
      >
        <div class="container-box label-style">
          <!--status-->
          <el-row>
            <el-form-item
              label="Status"
              prop="Status"
            >
              <el-select
                style="width: 200px"
                v-model="submitForm.status"
              >
                <el-option
                  v-for="i in status"
                  :key="i.value"
                  :label="i.label"
                  :value="i.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-row>
          <!--phone-->
          <el-row>
            <el-form-item
              style="width: 220px"
              label="Registration Phone（start with 0）"
              prop="account"
              :class="{'phone-require':phoneRequired}"
            >
              <el-input v-model="submitForm.account"></el-input>
            </el-form-item>
          </el-row>
          <!--Facebook ID-->
          <!--以ID判断是够处于编辑状态 编辑时显示 新增时不显示-->
          <el-row v-if="id">
            <el-form-item
              style="width: 200px"
              label="Facebook ID"
            >
              <el-input
                v-model="facebookId"
                disabled
              ></el-input>
            </el-form-item>
          </el-row>
          <el-row>
            <!--region-->
            <el-form-item
              label="Region"
              prop="regionId"
            >
              <el-select
                style="width: 200px"
                v-model="submitForm.regionId"
                @change="getTownships"
              >
                <el-option
                  v-for="rg in regions"
                  :key="rg.value"
                  :label="rg.text"
                  :value="rg.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <!--township-->
            <el-form-item
              label="Township"
              prop="townshipId"
            >
              <el-select
                style="width: 200px"
                v-model="submitForm.townshipId"
              >
                <el-option
                  v-for="ts in townshipData"
                  :key="ts.value"
                  :label="ts.text"
                  :value="ts.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-row>
          <!--street-->
          <el-row>
            <el-form-item
              label="Street"
              style="width: 200px"
              prop=""
            >
              <el-input v-model="submitForm.street"></el-input>
            </el-form-item>
          </el-row>
          <!--photo-->
          <el-row>
            <el-form-item
              label="Photo"
              class="agent-photo"
              prop=""
            >
              <uploadCoverImages ref="uploadCoverImages"></uploadCoverImages>
            </el-form-item>
          </el-row>
          <!--user name-->
          <el-row>
            <el-col class="name-require">
              <el-form-item
                label="User name"
                style="width: 200px"
                prop="name"
              >
                <el-input
                  v-model="submitForm.name"
                  class="name-label"
                ></el-input>
              </el-form-item>
              <div>Letter (a-z), number (0-9), underscore (_) only. 5-20 characters.</div>
            </el-col>
          </el-row>
          <!--分割线-->
          <div class="line-separat"></div>
          <h3>ShopGoGo app</h3>
          <!--Display phone to buyer-->
          <el-form-item label="Display phone to buyer">
            <!--<el-switch v-model="submitForm.displayPhone"></el-switch>-->
            <el-radio
              v-model="submitForm.displayPhone"
              label="1"
            >NO
            </el-radio>
            <el-radio
              v-model="submitForm.displayPhone"
              label="2"
            >YES
            </el-radio>
          </el-form-item>
          <!--Description-->
          <el-row>
            <el-form-item
              label="Description"
              prop="description"
            >
              <el-input
                style="min-width:500px;"
                type="textarea"
                :rows="5"
                maxlength="1500"
                v-model="submitForm.description"
              >
              </el-input>
            </el-form-item>
          </el-row>
          <!--分割线-->
          <div class="line-separat"></div>
          <h3>BestProperty app</h3>
          <!--Advertisement phones-->
          <el-row>
            <el-form-item
              label="Advertisement phones (separated by comma)"
              style="width: 400px"
            >
              <el-input v-model="submitForm.phone"></el-input>
            </el-form-item>
          </el-row>
          <!--Advertisement Email-->
          <el-row>
            <el-form-item
              label="Advertisement Email"
              style="width: 400px"
            >
              <el-input v-model="submitForm.email"></el-input>
            </el-form-item>
          </el-row>
          <div class="line-separat"></div>
          <h3>Internal use</h3>
          <!--Seller category-->
          <el-row>
            <span class="label-title">Seller category</span>
            <div class="container-box">
              <el-form-item class="label-vertical features-check">
                <el-checkbox-group v-model="submitForm.categoryIds">
                  <el-checkbox
                    v-for="i in sellerCategory"
                    :label="i.value"
                    :key="i.value"
                  >{{i.text}}
                  </el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </div>
          </el-row>
          <el-row>
            <el-form-item
              label="User's website"
              style="width: 400px"
              prop="street"
            >
              <el-input v-model="submitForm.website"></el-input>
            </el-form-item>
          </el-row>
          <!--facebook-->
          <el-row>
            <el-form-item
              label="User's facebook"
              style="width: 400px"
              prop="street"
            >
              <el-input v-model="submitForm.facebook"></el-input>
            </el-form-item>
          </el-row>
          <!--Notes (internal use)-->
          <el-row>
            <el-form-item
              label="Notes"
              prop="notes"
            >
              <el-input
                style="min-width:500px;"
                type="textarea"
                :rows="5"
                :maxlength="2000"
                v-model="submitForm.notes"
              >
              </el-input>
            </el-form-item>
          </el-row>
          <el-row>
            <el-checkbox v-model="submitForm.fromBackend">upload excel data from backend (electronics data)</el-checkbox>
          </el-row>
          <!--facebook messenger url-->
          <el-row>
            <el-form-item
              label="Facebook messenger url (example: http://m.me/username)"
              style="width: 400px"
            >
              <el-input v-model="submitForm.facebookMessengerUrl"></el-input>
            </el-form-item>
          </el-row>
          <el-row
            :gutter="40"
            type="flex"
            justify="center"
            style="padding:40px 0;"
          >
            <el-col :span="6">
              <el-button
                @click="cancelPutForm()"
                size="medium"
                type="info"
                style="width:100%"
              >
                Cancel
              </el-button>
            </el-col>
            <el-col :span="6">
              <el-button
                @click.native="uploadSubmitForm('submitForm')"
                v-loading.fullscreen.lock="fullscreenLoading"
                size="medium"
                type="success"
                style="width:100%"
              >
                Save
              </el-button>
            </el-col>
          </el-row>
        </div>
      </el-form>
    </div>
  </div>
</template>
<script>
  import Qs from "qs";
  import uploadCoverImages from "@/components/imageComponents/uploadCoverImages";
  // 英语JSON
  import regions from "@/json/region";
  import townships from "@/json/township";
  import sellerCategory from "@/json/sellerCategory";
  import {
    shopUserEdit,
    shopUserAdd,
    uploadUserPhotos,
    shopUserCheck,
    shopUserDetail
  } from "../../api/guc_api.js";

  export default {
    name: "newRestaurant",
    data() {
      return {
        //用户id
        id: "",
        facebookId: "",
        phoneRequired: true,
        //status数据
        status: [
          {
            label: "Active",
            value: "1"
          },
          {
            label: "Not interested",
            value: "0"
          },
          {
            label: "Stoped business",
            value: "3"
          },
          {
            label: "Called but no answer",
            value: "5"
          },
          {
            label: "Wrong phone number",
            value: "6"
          },
          {
            label: "Suspended",
            value: "4"
          },
          {
            label: "Deleted",
            value: "2"
          }
        ],
        regions,
        townships,
        townshipData: [],
        sellerCategory,
        submitForm: {
          // 表单数据必填字段 重新上传
          status: "1",
          name: '',
          regionId: '',
          townshipId: '',
          street: '',
          facebook: '',
          account: '',
          phone: '',
          email: '',
          notes: '',
          description: '',
          displayPhone: '',
          website: '',
          categoryIds: [],
          fromBackend:false,
          facebookMessengerUrl:''
        },
        // 添加表单修改数据和字段
        fullscreenLoading: false,
        loading: false,
        //总共有四处需要验证
        rules: {
          name: [
            {
              validator: (rule, value, callback) => {
                if (value === "") {
                  callback(new Error("please enter user name"));
                } else if (
                  /^[a-z0-9A-Z_\u1000-\u109F]{5,20}$/.test(value) === false
                ) {
                  callback(new Error("wrong format"));
                } else {
                  callback();
                }
              },
              trigger: "blur"
            }
          ],
          account: [
            {
              validator: (rule, value, callback) => {
                if (value === "") {
                  callback(new Error("please enter your phone number"));
                } else if (/^[0-9]*$/.test(value) === false) {
                  callback(new Error("number only"));
                } else if (/^0/.test(value) === false) {
                  callback(new Error("start with 0"));
                } else {
                  callback();
                }
              },
              trigger: "blur"
            }
          ],
          regionId: [
            {
              required: true,
              message: "please select region",
              trigger: "change"
            }
          ],
          townshipId: [
            {
              required: true,
              message: "please select township",
              trigger: "change"
            }
          ]
        },
        //表示是新建还是登录状态
        isNewCreate: true
      };
    },
    methods: {
      getTownships() {
        this.submitForm.townshipId = "";
        let townData = [];
        this.townships.forEach(item => {
          if (item.regionId === this.submitForm.regionId) {
            townData.push(item);
          }
        });
        this.townshipData = townData;
      },
      // message alert 用于前端错误提示信息
      messageToastErr(msg) {
        this.$message({
          showClose: true,
          message: msg,
          duration: 5000,
          type: "error"
        });
      },
      messageToastSuccess(msg) {
        this.$message({
          showClose: true,
          message: msg,
          duration: 5000,
          type: "success"
        });
      },
      // 编辑时获取用户id后初始化表单
      initForm() {
        this.loading = true;
        let params = {
          userId: this.id
        };
        //编辑的时候校验规则要改了 Registration Phone region 和township不再是必填
        //去掉Registration Phone 必填时 显示星星的类
        this.phoneRequired = false;
        //去掉不需要的校验规则
        this.rules = {
          name: [
            {
              validator: (rule, value, callback) => {
                if (value === "") {
                  callback(new Error("please enter user name"));
                } else if (
                  /^[a-z0-9A-Z_\u1000-\u109F]{1,20}$/.test(value) === false
                ) {
                  callback(new Error("wrong format"));
                } else {
                  callback();
                }
              },
              trigger: "change"
            }
          ]
        };
        shopUserDetail(params)
          .then(res => {
            if (res.data) {
              let obj = res.data;
              this.submitForm.status = obj.status + "";
              this.submitForm.name = this.$translateLang(obj.name||'','unicodeTozawgyi')||'';
              this.submitForm.regionId = obj.regionId;
              this.getTownships();
              this.submitForm.townshipId = obj.townshipId;
              this.submitForm.street = this.$translateLang(obj.street||'','unicodeTozawgyi')||'';
              this.submitForm.facebook = obj.facebook;
              this.submitForm.account = obj.account;
              this.submitForm.phone = obj.phone;
              this.submitForm.email = obj.email;
              this.submitForm.notes = this.$translateLang(obj.notes||'','unicodeTozawgyi')||'';
              this.submitForm.description = this.$translateLang(obj.description||'','unicodeTozawgyi')||'';
              this.submitForm.fromBackend=(obj.fixedUser==1)?true:false
              this.submitForm.facebookMessengerUrl=obj.facebookMessengerUrl
              //拿到的displayphone类型是number，要把它转换成字符串
              if(obj.displayPhone){
                this.submitForm.displayPhone = obj.displayPhone+'';
              }else{
                this.submitForm.displayPhone =null
              }
              this.submitForm.website = obj.website;
              this.facebookId = obj.facebookId;
              let userCategoryArr = [];
              obj.userCategory.forEach(item => {
                userCategoryArr.push(item.id);
              });
              this.submitForm.categoryIds = userCategoryArr || [];
              // Photos 初始化
              if (obj.photo) {
                this.$refs.uploadCoverImages.uploadPhotoList = [
                  {
                    url: obj.photo,
                    id: 0
                  }
                ];
              }
              this.loading = false;
            }
          })
          .catch(error => {
            this.loading = false;
            this.messageToastErr(error.response);
          });
      },
      removeAgentForm(submitForm) {
        this.$refs[submitForm].resetFields();
        this.$refs.uploadCoverImages.removeAllImage();
        this.submitForm.phone = "";
        this.submitForm.email = "";
        this.submitForm.categoryIds = "";
        this.submitForm.website = "";
        this.submitForm.facebook = "";
      },
      cancelPutForm() {
        this.$router.go(-1);
      },
      // 表单信息上传
      uploadSubmitForm(submitForm) {
        console.log(this.submitForm.fromBackend)

        this.$refs[submitForm].validate(valid => {
          if (!valid) {
            this.messageToastErr("Wrong Submit");
            return false;
          } else {
            // 通过校验，判断是新建还是编辑
            // 有id -- 则提交编辑信息
            if (this.id) {
              let formAjaxData = {
                id: this.id,
                status: this.submitForm.status,
                name: this.$translateLang(this.submitForm.name||'','zawgyiTounicode')||'',
                regionId: this.submitForm.regionId,
                townshipId: this.submitForm.townshipId,
                street: this.$translateLang(this.submitForm.street||'','zawgyiTounicode')||'',
                facebook: this.submitForm.facebook,
                account: this.submitForm.account,
                phone: this.submitForm.phone,
                email: this.submitForm.email,
                notes: this.$translateLang(this.submitForm.notes||'','zawgyiTounicode')||'',
                description: this.$translateLang(this.submitForm.description||'','zawgyiTounicode')||'',
                displayPhone: this.submitForm.displayPhone,
                website: this.submitForm.website,
                categoryIds: JSON.stringify(this.submitForm.categoryIds),
                fixedUser:this.submitForm.fromBackend?1:0,
                facebookMessengerUrl:this.submitForm.facebookMessengerUrl
              };
              let params = Qs.stringify(formAjaxData);
              let config = {
                "Content-Type": "multipart/form-data"
              };
              this.fullscreenLoading = true;
              //编辑的话就不用校验了
              shopUserEdit(params, config).then(res => {
                this.fullscreenLoading = false;
                if (res.data.errorID === 0) {
                  this.messageToastSuccess("Edit Success");
                  this.sendCoverPhoto(this.id);
                } else {
                  this.messageToastErr(res.data.message);
                }
              });
              // .catch((error) => {
              //   this.fullscreenLoading = false
              //   this.messageToastErr('error,please try again leter')
              // })
            }
            // 没有id，新增表单内容,新增之前先对用户名手机号进行验证
            else {
              let checkData = {
                account: this.submitForm.account,
                name: this.submitForm.name
              };
              this.fullscreenLoading = true;
              shopUserCheck(checkData)
                .then(res => {
                  this.fullscreenLoading = false;
                  if (res.data.errorID === 0) {
                    let formAjaxData = {
                      status: this.submitForm.status,
                      name: this.$translateLang(this.submitForm.name||'','zawgyiTounicode')||'',
                      regionId: this.submitForm.regionId,
                      townshipId: this.submitForm.townshipId,
                      street: this.$translateLang(this.submitForm.street||'','zawgyiTounicode')||'',
                      facebook: this.submitForm.facebook,
                      account: this.submitForm.account,
                      phone: this.submitForm.phone,
                      email: this.submitForm.email,
                      notes: this.$translateLang(this.submitForm.notes||'','zawgyiTounicode')||'',
                      description: this.$translateLang(this.submitForm.description||'','zawgyiTounicode')||'',
                      displayPhone: this.submitForm.displayPhone,
                      website: this.submitForm.website,
                      categoryIds: JSON.stringify(this.submitForm.categoryIds),
                      fixedUser:this.submitForm.fromBackend?1:0,
                      facebookMessengerUrl:this.submitForm.facebookMessengerUrl
                    };
                    let params = Qs.stringify(formAjaxData);
                    let config = {
                      "Content-Type": "multipart/form-data"
                    };
                    this.fullscreenLoading = true;
                    shopUserAdd(params, config)
                      .then(res => {
                        this.fullscreenLoading = false;
                        if (res.data.errorID === 0) {
                          //表单上传成功 拿到用户id
                          this.messageToastSuccess("New Create Success");
                          let id = res.data.object.id;
                          //表单提交成功后上传图片
                          this.sendCoverPhoto(id);
                        }
                      })
                      .catch(error => {
                        this.fullscreenLoading = false;
                        this.messageToastErr(
                          "New Create Failed,Please Try Again Later"
                        );
                      });
                  } else {
                    this.messageToastErr(res.data.message);
                  }
                })
                .catch(error => {
                  this.messageToastErr(
                    "Please Check Your Network And Try Again Later"
                  );
                });
            }
          }
        });
      },
      //Cover Photo 上传
      sendCoverPhoto(id) {
        let coverPhotoId = this.$refs.uploadCoverImages.delList;
        if (coverPhotoId && coverPhotoId.length > 0) {
        }
        let uploadPhotos = [];
        uploadPhotos = this.$refs.uploadCoverImages.uploadPhotoList;
        let formData = new FormData();
        //  是否有图片提交，有则提交图片，没有则显示表单提交成功信息
        let isToUpload = false;
        for (let i = 0; i < uploadPhotos.length; i++) {
          if (uploadPhotos[i].photoBlob) {
            formData.append("file", uploadPhotos[i].photoBlob);
            isToUpload = true;
          }
        }
        if (isToUpload) {
          formData.append("userId", id);
          let config = {
            "Content-Type": "multipart/form-data"
          };
          this.fullscreenLoading = true;
          uploadUserPhotos(formData, config)
            .then(res => {
              if (res.data.errorID === 0) {
                this.fullscreenLoading = false;
              } else {
                this.fullscreenLoading = false;
                this.messageToastErr(res.data.message);
              }
              this.reloadPage();
            })
            .catch(error => {
              this.fullscreenLoading = false;
              this.messageToastErr("error, please try again leter");
            });
        } else {
          //没有图片需要上传 取消加载动画
          this.fullscreenLoading = false;
          this.reloadPage();
        }
      },
      reloadPage() {
        this.$router.go(-1);
        // this.fullscreenLoading = true
        // if (this.isNewCreate) {
        //   this.removeAgentForm('submitForm')
        //   this.fullscreenLoading = false
        // } else {
        //   this.initForm()
        //   this.fullscreenLoading = false
        // }
      }
    },
    components: {
      uploadCoverImages
    },
    mounted() {
      window.scrollTo(0, 0);
      this.id = this.$route.query.id || "";
      if (this.id) {
        this.isNewCreate = false;
        this.initForm();
      }
    }
  };
</script>
<style scoped>
  .line-separat {
    border-bottom: 1px solid #e6e6e6;
    margin: 10px 0;
  }
</style>
<style>
  .page-title {
    padding: 20px 40px;
    border-bottom: 1px solid #e6e6e6;
    font-size: 20px;
  }

  .food-content-box .container-padding {
    padding: 20px 40px 0 40px;
  }

  .label-title {
    display: block;
    line-height: 28px;
    padding: 0 0 10px 0;
    font-size: 14px;
    color: #606266;
  }

  .label-vertical .el-form-item__label {
    width: 100%;
  }

  .features-check .el-checkbox {
    width: 20%;
  }

  .features-check .el-checkbox + .el-checkbox {
    margin-left: 0;
  }

  .features-check.el-form-item {
    display: block !important;
  }

  .bottom-line {
    border-bottom: 1px solid #e6e6e6;
  }

  .margin-line {
    margin: 10px 0;
  }

  .list-info {
    text-align: center;
    display: block;
  }

  .name-require::before {
    content: "*";
    color: #f56c6c;
    margin-right: 4px;
    position: relative;
    top: 5px;
  }

  .name-label {
    margin-left: -8px;
  }

  .phone-require::before {
    content: "*" !important;
    color: #f56c6c;
    margin-right: 4px;
    position: relative;
    top: 20px;
    left: -8px;
  }
</style>
